import { getFilterListByCanShowBtn } from './utils';

// 超过两个数量
const isMoreThanTwoNum = list => list.length > 2

// 获取元素位置
const getPos = (list, index) => ({
  start: index == 0,
  center: index > 0 && index < list.length - 1,
  end: index == list.length - 1
})

// 根据元素位置获取对应的margin
const getMarginStyleByPos = pos => {
  let style = ''
  if (pos.start) style = 'marginRight: 10px;'
  if (pos.center) style = 'margin: 0 10px;'
  if (pos.end) style = 'marginLeft: 10px;'
  return style
}

// 渲染el-button
const renderElButton = (h, item, row) => (
  <el-button
    slot={item.slot}
    type={item.type ?? 'text'}
    disabled={item.disabled}
    size={item.size ?? 'mini'}
    onClick={item.confirmTitle ? () => {} : () => item.method(row)} // confirmTitle存在，证明当前为el-popconfirm，不走按钮点击事件
  >{item.label}
  </el-button>
)

// 渲染el-popconfirm 按钮气泡确认框
const renderElPopconfirm = (h, item, row, pos) => (
  <el-popconfirm
    title={item.confirmTitle}
    style={getMarginStyleByPos(pos)}
    onConfirm={() => { item.method(row) }}
  >
    { renderElButton(h, item, row) }
  </el-popconfirm>
)

// 渲染el-dropdown 下拉按钮
const renderElDropdown = (h, actionList, renderAction) => {
  const dropdownLinkStyle = `cursor: pointer;
    color: #409EFF; font-size: 12px; font-weight: 500;`; // 下拉按钮样式
  const iconArrowDownStyle = `font-size: 12px;`; // 下拉
  const buttonPaddingStyle = `padding: 0 20px`;
  return (<el-dropdown>
    <span style={dropdownLinkStyle}>
      更多<i class="el-icon-arrow-down" style={iconArrowDownStyle}></i>
    </span>
    <el-dropdown-menu slot="dropdown">
      { actionList.map((item, index) => <div style={buttonPaddingStyle}>{renderAction(item, getPos(actionList, index))}</div>) }
    </el-dropdown-menu>
  </el-dropdown>)
}

// 获取action
const getActionRender = (h, row) => {
  return (item, pos) => {
    if (item.confirmTitle) return renderElPopconfirm(h, { ...item, slot: 'reference' }, row, pos)
    return renderElButton(h, item, row)
  }
}

// 获取actions
const getActionsRender = (h, renderAction) => {
  return actionList => (
    <div class="table-action">{
      actionList.map((item, index) => renderAction(item, getPos(actionList, index)))
    }</div>
  )
}

/**
 * @param { h } 要渲染的h函数
 * @param { row } 当前操作表格行的row数据
 * @param { actionList } 要渲染的按钮列表集合
 * @param { isEnableDropdown } 是否启用多个按钮下拉模式，默认不启用
*/
export const getTableAction = ({ h, row, actionList, showBtn }, isEnableDropdown = false) => {
  const renderAction = getActionRender(h, row) // 单个action操作项的渲染方法
  const renderActions = getActionsRender(h, renderAction) // 所有actions操作集合的渲染方法
  const filteredList = getFilterListByCanShowBtn(actionList, showBtn)
  if (isEnableDropdown && isMoreThanTwoNum(list)) {
    return <el-row>
      { renderAction(filteredList[0]) }
      <el-divider direction="vertical"></el-divider>
      { renderElDropdown(h, filteredList.slice(1), renderAction) }
    </el-row>
  }
  return renderActions(filteredList)
}
